package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;


@Controller
public class LoginController {


    @RequestMapping("/login")
    @ResponseBody
    //Model把信息放到请求中不可用,session作用域更大,同个会话中可用
    public JsonResult login(String username, String password) {
        try {
            //获取subject主体
            Subject subjeuct = SecurityUtils.getSubject();

            //对密码进行加密
            Md5Hash md5Hash = new Md5Hash(password, username, 2);
            //把前端传过来的参数封装为令牌
            UsernamePasswordToken token = new UsernamePasswordToken(username, md5Hash.toString());
            //使用shiro提供的API来登录(必须要使用该方法,才会改变subject的认证状态)
            subjeuct.login(token);
            return new JsonResult();
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            //返回错误信息
            return new JsonResult(false, "用户名不存在");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return new JsonResult(false, "密码错误");
        } catch (DisabledAccountException e) {
            e.printStackTrace();
            return new JsonResult(false, e.getMessage());
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return new JsonResult(false, e.getMessage());
        }
    }

   /* //注销操作
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();//销毁会话
        return "redirect:/login.html";
    }*/
}
